package funcs.db;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class QDBMysql {
	private String connStr = "";
	private Connection con = null;
	private Statement stmt = null;

	public QDBMysql(String str) {
		this.connStr = str;
	}

	public boolean OpenDB() {
		try {
			Class.forName("org.gjt.mm.mysql.Driver").newInstance();
			con = DriverManager.getConnection(connStr);
			stmt = con.createStatement();
		} catch (Exception ex) {
			System.out.println("Open database error.");
			return false;
		}

		return true;
	}

	public int ExecuteNonQuery(String sql) {
		try {
			return stmt.executeUpdate(sql);
		} catch (Exception ex) {
			System.out.println("Execute error:" + sql);
			return -1;
		}
	}

	public ResultSet ExecuteResultSet(String sql) {
		try {
			return stmt.executeQuery(sql);
		} catch (Exception ex) {
			System.out.println("Execute error:" + sql);
			return null;
		}
	}

	public PreparedStatement getPS(String sql) {
		try {
			return con.prepareStatement(sql);
		} catch (SQLException e) {
			e.printStackTrace();
		}

		return null;
	}

	public int ExecuteNonQuery(PreparedStatement ps) {
		try {
			int ret = ps.executeUpdate();
			ps.close();

			return ret;
		} catch (Exception ex) {
			System.out.println("Execute error");
			return -1;
		}
	}

	public ResultSet ExecuteResultSet(PreparedStatement ps) {
		try {
			ResultSet ret = ps.executeQuery();
			return ret;
		} catch (Exception ex) {
			System.out.println("Execute error");
			return null;
		}
	}

	public boolean CloseDB() {
		try {
			stmt.close();
			con.close();
		} catch (Exception ex) {
			System.out.println("Close database error.");
			return false;
		}

		return true;
	}

	public void setAutoCommit(boolean isAutoCommit) {
		try {
			con.setAutoCommit(isAutoCommit);
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}

	public void Commit() {
		try {
			con.commit();
			con.setAutoCommit(true);
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}
}
